package com.tancire.net.service.impl;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.alibaba.fastjson2.JSONObject;
import com.tancire.common.core.domain.entity.SysUser;
import com.tancire.common.enums.UserSource;
import com.tancire.common.exception.net.NetActivityException;
import com.tancire.common.utils.DateUtils;
import com.tancire.common.utils.SecurityUtils;
import com.tancire.common.utils.StringUtils;
import com.tancire.net.domain.CrmCompany;
import com.tancire.net.domain.NetUser;
import com.tancire.net.domain.UpdatePass;
import com.tancire.net.mapper.CrmCompanyMapper;
import com.tancire.net.service.ICrmCompanyService;
import com.tancire.net.service.INetUserService;
import com.tancire.net.utils.SysConfigUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Base64;
import java.util.Date;
import java.util.List;

/**
 * 客户管理Service业务层处理
 *
 * @author 陈超
 * @date 2023-12-24
 */
@Service
public class CrmCompanyServiceImpl implements ICrmCompanyService {

    @Resource
    private CrmCompanyMapper crmCompanyMapper;

    @Resource
    private SysConfigUtils sysConfigUtils;

    @Resource
    private INetUserService netUserService;

    /**
     * 查询客户管理
     *
     * @param id 客户管理主键
     * @return 客户管理
     */
    @Override
    public CrmCompany selectCrmCompanyById(Long id) {
        return crmCompanyMapper.selectCrmCompanyById(id);
    }

    /**
     * 查询客户管理列表
     *
     * @param crmCompany 客户管理
     * @return 客户管理
     */
    @Override
    public List<CrmCompany> selectCrmCompanyList(CrmCompany crmCompany) {
        return crmCompanyMapper.selectCrmCompanyList(crmCompany);
    }

    /**
     * 新增客户管理
     *
     * @param crmCompany 客户管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertCrmCompany(CrmCompany crmCompany) {
        // 初始化账号信息
        String initPass = sysConfigUtils.getConfigString("crm.company.initPassword");
        if (StringUtils.isBlank(initPass)) {
            initPass = "123456";
        }
        crmCompany.setCustomerPassword(SecurityUtils.encryptPassword(initPass));
        if (StringUtils.isBlank(crmCompany.getCustomerAccount())) {
            throw new NetActivityException("账号不能为空");
        }
        CrmCompany sysCompany = crmCompanyMapper.selectCrmCompanyByAccount(crmCompany.getCustomerAccount());
        if (null != sysCompany && null != sysCompany.getId()) {
            throw new NetActivityException("账号名重复");
        }
        crmCompany.setId(IdUtil.getSnowflakeNextId());
        crmCompany.setCreateBy(SecurityUtils.getUserId() + "");
        crmCompany.setCreateTime(DateUtils.getNowDate());
        return crmCompanyMapper.insertCrmCompany(crmCompany);
    }

    /**
     * 修改客户管理
     *
     * @param crmCompany 客户管理
     * @return 结果
     */
    @Override
    public int updateCrmCompany(CrmCompany crmCompany) {
        crmCompany.setUpdateTime(DateUtils.getNowDate());
        return crmCompanyMapper.updateCrmCompany(crmCompany);
    }

    /**
     * 批量删除客户管理
     *
     * @param ids 需要删除的客户管理主键
     * @return 结果
     */
    @Override
    public int deleteCrmCompanyByIds(Long[] ids) {
        return crmCompanyMapper.deleteCrmCompanyByIds(ids);
    }

    /**
     * 删除客户管理信息
     *
     * @param id 客户管理主键
     * @return 结果
     */
    @Override
    public int deleteCrmCompanyById(Long id) {
        return crmCompanyMapper.deleteCrmCompanyById(id);
    }

    @Override
    public SysUser selectCrmCompanyByAccount(String account) {
        SysUser sysUser = new SysUser();
        try {
            CrmCompany crmCompany = crmCompanyMapper.selectCrmCompanyByAccount(account);
            sysUser.setUserName(crmCompany.getCustomerAccount());
            sysUser.setPassword(crmCompany.getCustomerPassword());
            sysUser.setNickName(crmCompany.getCustomerName());
            sysUser.setUserId(crmCompany.getId());
            sysUser.setStatus(crmCompany.getCustomerStatus() + "");
            // 标记为企业账号
            sysUser.setUserSource(UserSource.COMPANY.getCode());
        } catch (Exception e) {
            throw new NetActivityException("未查询到账号信息");
        }
        return sysUser;
    }

    /**
     * 绑定微信小程序
     *
     * @param crmCompany
     */
    @Override
    public void bindMinApp(CrmCompany crmCompany) {
        String publicKey = sysConfigUtils.getConfigString("crm.bind.publicKey");
        RSA rsa = new RSA(null, publicKey);
        byte[] decode = Base64.getDecoder().decode(crmCompany.getMiniAppCode());
        byte[] decrypt = rsa.decrypt(decode, KeyType.PublicKey);
        String info = new String(decrypt, CharsetUtil.CHARSET_UTF_8);
        JSONObject jsonObject = JSONObject.parseObject(info);
        String account = jsonObject.getString("account");
        String code = jsonObject.getString("code");
        // 查询账户信息
        NetUser netUser = this.netUserService.selectNetUserByAccount(account);
        if (null != netUser && null != netUser.getId()) {
            CrmCompany upData = new CrmCompany();
            upData.setId(SecurityUtils.getUserId());
            upData.setMiniAppId(netUser.getId());
            upData.setMiniAppAccount(netUser.getAccount());
            upData.setMiniAppCode(code);
            upData.setMiniAppStatus(1);
            upData.setMiniAppTime(new Date());
            this.crmCompanyMapper.updateCrmCompany(upData);
        } else {
            throw new NetActivityException("获取账号信息失败");
        }
    }

    /**
     * 修改密码
     *
     * @param updatePass
     */
    @Override
    public void updatePassword(UpdatePass updatePass) {
        // 判断旧密码不能为空
        if (StringUtils.isBlank(updatePass.getOldPass())) {
            throw new NetActivityException("旧密码不能为空");
        }
        // 查询数据库密码
        CrmCompany company = this.crmCompanyMapper.selectCrmCompanyById(SecurityUtils.getUserId());
        if (null == company) {
            throw new NetActivityException("获取账号信息失败");
        }
        // 获取密码
        String customerPassword = company.getCustomerPassword();
        if (!SecurityUtils.matchesPassword(updatePass.getOldPass(), customerPassword)) {
            throw new NetActivityException("旧密码输入错误");
        }
        String newPass = updatePass.getNewPass();
        if (StringUtils.isBlank(newPass)) {
            throw new NetActivityException("新密码不能为空");
        }
        if (newPass.contains(" ")) {
            throw new NetActivityException("新密码不能包含空格");
        }
        CrmCompany upCompany = new CrmCompany();
        upCompany.setId(SecurityUtils.getUserId());
        upCompany.setCustomerPassword(SecurityUtils.encryptPassword(newPass));
        this.crmCompanyMapper.updateCrmCompany(upCompany);
    }

    /**
     * 重置客户密码
     *
     * @param id
     * @return
     */
    @Override
    public int resetPassword(Long id) {
        String initPass = sysConfigUtils.getConfigString("crm.company.initPassword");
        if (StringUtils.isBlank(initPass)) {
            initPass = "123456";
        }
        CrmCompany upCompany = new CrmCompany();
        upCompany.setId(id);
        upCompany.setCustomerPassword(SecurityUtils.encryptPassword(initPass));
        return this.crmCompanyMapper.updateCrmCompany(upCompany);
    }

    /**
     * 停用账号
     *
     * @param id
     * @return
     */
    @Override
    public int disabledAccount(Long id) {
        CrmCompany upCompany = new CrmCompany();
        upCompany.setId(id);
        upCompany.setCustomerStatus(1);
        return this.crmCompanyMapper.updateCrmCompany(upCompany);
    }

    /**
     * 启用账号
     *
     * @param id
     * @return
     */
    @Override
    public int enabledAccount(Long id) {
        CrmCompany upCompany = new CrmCompany();
        upCompany.setId(id);
        upCompany.setCustomerStatus(0);
        return this.crmCompanyMapper.updateCrmCompany(upCompany);
    }
}
